package cn.angis.quartz.util;

import cn.angis.common.constant.Constant;
import cn.angis.common.constant.ScheduleConstants;
import cn.angis.common.util.ExceptionUtil;
import cn.angis.quartz.model.Joblog;
import cn.angis.quartz.model.SysJob;
import cn.angis.quartz.service.JoblogService;
import org.apache.commons.beanutils.BeanUtils;
import org.noear.solon.Solon;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;

/**
 * 抽象quartz调用
 *
 * @author ruoyi
 */
public abstract class AbstractQuartzJob implements Job
{
    private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);

    /**
     * 线程本地变量
     */
    private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException
    {
        SysJob sysJob = new SysJob();
        try {
            BeanUtils.copyProperties(sysJob, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES));
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        try
        {
            before(context, sysJob);
            if (sysJob != null)
            {
                doExecute(context, sysJob);
            }
            after(context, sysJob, null);
        }
        catch (Exception e)
        {
            log.error("任务执行异常  - ：", e);
            after(context, sysJob, e);
        }
    }

    /**
     * 执行前
     *
     * @param context 工作执行上下文对象
     * @param sysJob 系统计划任务
     */
    protected void before(JobExecutionContext context, SysJob sysJob)
    {
        threadLocal.set(new Date());
    }

    /**
     * 执行后
     *
     * @param context 工作执行上下文对象
     * @param sysJob 系统计划任务
     */
    protected void after(JobExecutionContext context, SysJob sysJob, Exception e)
    {
        Date startTime = threadLocal.get();
        threadLocal.remove();

        final Joblog joblog = new Joblog();
        joblog.setName(sysJob.getName());
        joblog.setJobGroup(sysJob.getJobGroup());
        joblog.setInvokeTarget(sysJob.getInvokeTarget());
        long runMs = new Date().getTime() - startTime.getTime();
        joblog.setJobMessage(joblog.getName() + " 总共耗时：" + runMs + "毫秒");
        if (e != null)
        {
            joblog.setStatus(Constant.DISABLE);
            String errorMsg = ExceptionUtil.getExceptionMessage(e).substring(0, 2000);
            joblog.setExceptionInfo(errorMsg);
        }
        else
        {
            joblog.setStatus(Constant.ENABLE);
        }

        // 写入数据库当中
        Solon.app().context().getBean(JoblogService.class).save(joblog);
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param sysJob 系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception;
}
